package thread.pool;

import java.util.concurrent.*;

public class CommonThreadPoolDemo {

    public static void main(String[] args) {
        // 1. newFixedThreadPool - 固定大小线程池
        fixedThreadPoolExample();

        // 2. newCachedThreadPool - 缓存线程池
        cachedThreadPoolExample();

        // 3. newSingleThreadExecutor - 单线程线程池
        singleThreadExecutorExample();

        // 4. newScheduledThreadPool - 定时线程池
        scheduledThreadPoolExample();

        // 5. 自定义线程池示例
        customThreadPoolExample();
    }

    /**
     * 固定大小线程池示例
     */
    public static void fixedThreadPoolExample() {
        System.out.println("=== Fixed Thread Pool Example ===");
        ExecutorService fixedThreadPool = Executors.newFixedThreadPool(3);

        for (int i = 0; i < 5; i++) {
            final int taskId = i;
            fixedThreadPool.submit(() -> {
                System.out.println("Fixed Thread Pool Task " + taskId + " is running on thread " + Thread.currentThread().getName());
                try {
                    Thread.sleep(2000); // 模拟任务执行
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println("Fixed Thread Pool Task " + taskId + " is completed");
            });
        }

        fixedThreadPool.shutdown(); // 关闭线程池
    }

    /**
     * 缓存线程池示例
     */
    public static void cachedThreadPoolExample() {
        System.out.println("\n=== Cached Thread Pool Example ===");
        ExecutorService cachedThreadPool = Executors.newCachedThreadPool();

        for (int i = 0; i < 5; i++) {
            final int taskId = i;
            cachedThreadPool.submit(() -> {
                System.out.println("Cached Thread Pool Task " + taskId + " is running on thread " + Thread.currentThread().getName());
                try {
                    Thread.sleep(1000); // 模拟任务执行
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println("Cached Thread Pool Task " + taskId + " is completed");
            });
        }

        cachedThreadPool.shutdown(); // 关闭线程池
    }

    /**
     * 单线程线程池示例
     */
    public static void singleThreadExecutorExample() {
        System.out.println("\n=== Single Thread Executor Example ===");
        ExecutorService singleThreadExecutor = Executors.newSingleThreadExecutor();

        for (int i = 0; i < 5; i++) {
            final int taskId = i;
            singleThreadExecutor.submit(() -> {
                System.out.println("Single Thread Executor Task " + taskId + " is running on thread " + Thread.currentThread().getName());
                try {
                    Thread.sleep(500); // 模拟任务执行
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println("Single Thread Executor Task " + taskId + " is completed");
            });
        }

        singleThreadExecutor.shutdown(); // 关闭线程池
    }

    /**
     * 定时线程池示例
     */
    public static void scheduledThreadPoolExample() {
        System.out.println("\n=== Scheduled Thread Pool Example ===");
        ScheduledExecutorService scheduledThreadPool = Executors.newScheduledThreadPool(2);

        // 延迟执行任务
        scheduledThreadPool.schedule(() -> {
            System.out.println("Scheduled task executed after 3 seconds on thread " + Thread.currentThread().getName());
        }, 3, TimeUnit.SECONDS);

        // 周期性执行任务 - 固定频率
        scheduledThreadPool.scheduleAtFixedRate(() -> {
            System.out.println("Periodic task executed at fixed rate on thread " + Thread.currentThread().getName() + " at " + System.currentTimeMillis());
        }, 1, 2, TimeUnit.SECONDS);

        // 周期性执行任务 - 固定延迟
        scheduledThreadPool.scheduleWithFixedDelay(() -> {
            System.out.println("Periodic task executed with fixed delay on thread " + Thread.currentThread().getName() + " at " + System.currentTimeMillis());
            try {
                Thread.sleep(500); // 模拟任务执行时间
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }, 1, 2, TimeUnit.SECONDS);

        // 运行5秒后关闭
        try {
            Thread.sleep(5000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        scheduledThreadPool.shutdown();
    }

    /**
     * 自定义线程池示例
     */
    public static void customThreadPoolExample() {
        System.out.println("\n=== Custom Thread Pool Example ===");

        // 创建自定义线程池
        ThreadPoolExecutor customThreadPool = new ThreadPoolExecutor(
                2,                          // 核心线程数
                4,                          // 最大线程数
                60L,                        // 空闲线程存活时间
                TimeUnit.SECONDS,           // 时间单位
                new LinkedBlockingQueue<>(3), // 任务队列
                Executors.defaultThreadFactory(), // 线程工厂
                new ThreadPoolExecutor.CallerRunsPolicy() // 拒绝策略
        );

        // 提交任务
        for (int i = 0; i < 6; i++) {
            final int taskId = i;
            customThreadPool.submit(() -> {
                System.out.println("Custom Thread Pool Task " + taskId + " is running on thread " + Thread.currentThread().getName());
                try {
                    Thread.sleep(2000); // 模拟任务执行
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println("Custom Thread Pool Task " + taskId + " is completed");
            });
        }

        // 监控线程池状态
        monitorThreadPool(customThreadPool, "初始状态");

        try {
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        monitorThreadPool(customThreadPool, "运行一段时间后");

        // 关闭线程池
        customThreadPool.shutdown();
        monitorThreadPool(customThreadPool, "调用shutdown()后");

        try {
            if (!customThreadPool.awaitTermination(10, TimeUnit.SECONDS)) {
                customThreadPool.shutdownNow();
            }
        } catch (InterruptedException e) {
            customThreadPool.shutdownNow();
        }

        monitorThreadPool(customThreadPool, "完全关闭后");
    }

    /**
     * 监控线程池状态
     */
    private static void monitorThreadPool(ThreadPoolExecutor threadPool, String stage) {
        System.out.println("[" + stage + "] 线程池状态: " +
                "核心线程数=" + threadPool.getCorePoolSize() +
                ", 活动线程数=" + threadPool.getActiveCount() +
                ", 最大线程数=" + threadPool.getMaximumPoolSize() +
                ", 线程池大小=" + threadPool.getPoolSize() +
                ", 队列大小=" + threadPool.getQueue().size() +
                ", 已完成任务数=" + threadPool.getCompletedTaskCount() +
                ", 总任务数=" + threadPool.getTaskCount());
    }
}
